package xrc.vo;

import org.springframework.util.StringUtils;
import xrc.utils.ValidatorUtil;
import xrc.validator.IsMobile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 手机号码校验规则
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {
    
    private boolean required = false;
    
    @Override
    public void initialize(IsMobile constraintAnnotation) {
         required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (required) {
            // 直接验证手机号码
            return ValidatorUtil.isMobile(value);
        } else {
            if (StringUtils.isEmpty(value)) {
                // 如果手机号码为空值 则直接返回true
                return true;
            } else {
                // 如果手机号码不为空值 则对手机号码验证
                return ValidatorUtil.isMobile(value);
            }
        }
    }
}
